import type {
	CommonResult,
	LoginParams,
	LoginResult,
	RegisterParams,
} from '@/types'
import { http } from '@/utils/http'
import { getUserApiPrefix, getAuthApiPrefix } from '@/utils/config'

/**
 * 用户名和密码登录，获取token
 * @param data
 */
export const loginAPI = (data : LoginParams) => {
	return http<LoginResult>({
		url: `${getAuthApiPrefix()}/oauth2/token`,
		method: 'POST',
		data,
	})
}

/**
 * 退出登录
 */
export const logoutAPI = () => {
	return http<CommonResult>({
		url: `${getAuthApiPrefix()}/token/logout`,
		method: 'DELETE',
	})
}

/**
 * 刷新token
 * @param refreshToken 刷新令牌
 */
export const refreshTokenAPI = (refreshToken: string) => {
	return http<LoginResult>({
		url: `${getAuthApiPrefix()}/oauth2/token`,
		method: 'POST',
		data: {
			grant_type: 'refresh_token',
			refresh_token: refreshToken
		}
	})
}

/**
 * Token信息接口
 */
export interface TokenInfo {
	active: boolean;
	aud: string[];
	client_id: string;
	exp: number;
	iat: number;
	iss: string;
	jti: string;
	license: string;
	nbf: number;
	refresh_token: string;
	scope: string[];
	sub: string;
	token_type: string;
	user_id: number;
	user_info: any;
	username: string;
}

/**
 * 检查token有效性
 * @param token 待检查的token
 */
export const checkTokenAPI = (token: string) => {
	return http<TokenInfo>({
		url: `${getAuthApiPrefix()}/token/check_token?token=${token}`,
		method: 'GET'
	})
}



/**
 * 注册
 * @param params
 */
export const registerAPI = (params : RegisterParams) => {
	return http<CommonResult>({
		url: `${getUserApiPrefix()}/register/custom`,
		method: 'POST',
		data: params,
	})
}

